package com.bosicen.crm.web.controller.sysmanage;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bosicen.crm.dao.entity.Dealer;
import com.bosicen.crm.dao.entity.User;
import com.bosicen.crm.service.sysmanage.DealerServiceImpl;
import com.bosicen.crm.tools.AppUtil;
import com.bosicen.crm.tools.Page;
import com.google.gson.Gson;

/***
 * 经销商信息Controller
 * @author tigerlei
 *
 */
@Controller
@RequestMapping("/basicinfo")
public class DealerController {
	
	@Autowired
	public DealerServiceImpl dealerService;
	
	
	/**
	 * 新增,修改经销商信息
	 * @param dealer
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addDealer/{type}")
	public String addDealer(HttpServletRequest request,@PathVariable("type") Integer type){
		String id = request.getParameter("id");
		Dealer dealer = null;
		if(type != 0 && StringUtils.isNotBlank(id)){
			dealer = this.dealerService.findDealerById(AppUtil.ObjectToInt(id));
		}
		request.setAttribute("dealer", dealer);
		return "sysmanage/addDealer";
	}
	
	
	/**
	 * 新增/修改经销商信息
	 * @param dealer
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/cudDealer/{type}")
	public void saveDealer(Dealer dealer, HttpServletRequest request, @PathVariable("type") Integer type, Writer writer) {
		boolean flag = false;
		Gson gson = new Gson();
		User user = (User) request.getSession().getAttribute("userinfo");
		dealer.setCompanyid(user.getCompanyid());
		try {
			if (dealer != null && dealer.getId()==0) {
				dealer.setCreatedate(new Date());
			}
			switch (type) {
				case 0: flag = dealerService.delDealer(dealer); break;
				case 1: flag = dealerService.saveOrUpdateDealer(dealer); break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.write(gson.toJson(flag));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 经销商列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dealerlist")
	public String findDealerlist(Dealer dealer,HttpServletRequest request) {
		Page page = new Page();
		page.setEveryPage(10);
		page.setCurrentPage(AppUtil.ObjectToInt(request.getParameter("pageno")));
		User user = (User) request.getSession().getAttribute("userinfo");
		dealer.setCompanyid(user.getCompanyid());
		page = dealerService.findDealer4Page(dealer, page);
		request.setAttribute("page",page);
		request.setAttribute("dealer", dealer);
		return "sysmanage/dealer_list";
	}
	
}
